package org.openfans.domain;

import java.util.Date;
import java.util.Set;

import org.openfans.util.WebUtil;

/**
 * 
 * Desc：用户的一次收藏<br>
 * Date：2007-3-8<br>
 * 
 * @author pesome<br>
 * @email:pesome@gmail.com<br>
 */
public class FansSnippet extends PersistentObject {
	private int id;

	private Fans fans;

	private Snippet snippet;

	private boolean privat;

	/**
	 * Each user can give the sinppet it's owner title
	 */
	private String title;

	/**
	 * 为了节约数据库,多个FansSnippet共享一个descn,这里不存入数据库
	 */
	private String descn;

	/**
	 * 用户自己的网摘使用的
	 */
	private Set<Tag> tagSet;

	private Date snippetDate;

	public String getDescn() {
		return descn;
	}

	public void setDescn(String descn) {
		this.descn = descn;
	}

	public Fans getFans() {
		return fans;
	}

	public void setFans(Fans fans) {
		this.fans = fans;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Snippet getSnippet() {
		return snippet;
	}

	public void setSnippet(Snippet snippet) {
		this.snippet = snippet;
	}

	public Date getSnippetDate() {
		return snippetDate;
	}

	public void setSnippetDate(Date snippetDate) {
		this.snippetDate = snippetDate;
	}

	public Set<Tag> getTagSet() {
		return tagSet;
	}

	public void setTagSet(Set<Tag> tagSet) {
		this.tagSet = tagSet;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public boolean isPrivat() {
		return privat;
	}

	public void setPrivat(boolean privat) {
		this.privat = privat;
	}

	/**
	 * 
	 * 第一次摘录,需先保存这个snippet
	 */
	public void saveNewSnippet() {
		Snippet s = this.getSnippet();
		String url = s.getUrl();
		String title = WebUtil.getTitle(url);
		// 如果从网页获取title失败,则使用第一次网摘的用户自定义title
		if (null == title || title.trim().length() == 0) {
			s.setTitle(this.getTitle());
		} else {
			s.setTitle(title);
		}
		// 不为private的网摘才更新tag,数量和描述
		if (!this.isPrivat()) {
			s.setTagSet(this.getTagSet());
			s.setSnippetCount(1);
			// 使用第一个收藏者的descn作为该网摘的描述
			s.setDescn(this.getDescn());
		}
		s.setPrivat(this.isPrivat());
		s.setFans(this.getFans());
		s.setSnippetDate(new Date());
		this.getPersistence().save(s);
		this.save();
	}

	/**
	 * 用户收藏已经存在的网摘
	 * @param s
	 */
	public void saveExitSnippet(Snippet s) {
		s.setDescn(this.getDescn());
		// 用户公开这个收藏,才进行相应操作
		if (!this.isPrivat()) {
			s.increaseSnippetCount();		
			s.getTagSet().addAll(this.getTagSet());
			// 之前一直是私有收藏
			if (s.isPrivat()) {
				s.setPrivat(false);
				s.setFans(this.getFans());
				s.setSnippetDate(new Date());
			}
		}
		this.setSnippet(s);
		this.save();
	}
}
